﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Text;
using System.Data;
using System.Data.SqlClient;
using System.IO;
using System.Xml;
using System.Xml.Serialization;

namespace PIM_ATE.Mods
{
    class ClsDataConfigBuilder : ClsDataConfigBase
    {
        public ProcodeINFO cProcodeINFO { get { return m_cProceodeINFO; } }
        public string sProcode { get { return m_sProcode; } }
        public string sVerConfig { get { return m_sVerConfig; } }
        public string sVerSpec { get { return m_sVerSpec; } }

        public ClsDataConfigBuilder(string alias)
            : base(alias)
        {
            CONFIG_TYPE = "RF";
            CONDITION_SQL = " and [Type] = '" + CONFIG_TYPE + "';";
        }

        #region static function

        //public static bool createConfigDataTable()
        //{
        //    string strSql = "CREATE TABLE \"PIMConfig\" (" +
        //                    "\"ID\" INT NOT NULL identity(1,1) PRIMARY KEY, " +
        //                    "\"ProCode\" NVARCHAR(100) NOT NULL, " +
        //                    "\"TestNo\" VARCHAR(50) NOT NULL, " +
        //                    "\"SaveNo\" VARCHAR(50) NOT NULL, " +
        //                    "\"PIMItemName\" NVARCHAR(100) NOT NULL, " +
        //                    "\"PIMType\" NVARCHAR(50) NOT NULL, " +
        //                    "\"ProCH\" NVARCHAR(50) NOT NULL, " +
        //                    "\"KEYWP\" NVARCHAR(50) NOT NULL, " +
        //                    "\"IsSweepTest\" NVARCHAR(10) NOT NULL, " +
        //                    "\"F1Freq\" VARCHAR(50) NOT NULL, " +
        //                    "\"F2Freq\" VARCHAR(50) NOT NULL, " +
        //                    "\"PIMFreq\" VARCHAR(50) NOT NULL, " +
        //                    "\"TXH\" VARCHAR(50) NOT NULL, " +
        //                    "\"TXL\" VARCHAR(50) NOT NULL, " +
        //                    "\"RXH\" VARCHAR(50) NOT NULL, " +
        //                    "\"RXL\" VARCHAR(50) NOT NULL, " +
        //                    "\"F1Power\" VARCHAR(50) NOT NULL, " +
        //                    "\"F2Power\" VARCHAR(50) NOT NULL, " +
        //                    "\"PIMOrder\" VARCHAR(50) NOT NULL, " +
        //                    "\"TestTime\" VARCHAR(50) NOT NULL, " +
        //                    "\"SpecReg\" NVARCHAR(50) NOT NULL, " +
        //                    "\"SpecUnit\" NVARCHAR(50) NOT NULL, " +
        //                    "\"IsKnock\" NVARCHAR(10) NOT NULL, " +
        //                    "\"ProGain\" VARCHAR(50) NOT NULL, " +
        //                    "\"Message\" NVARCHAR(200) NOT NULL, " +
        //                    "\"Check\" VARCHAR(50) NOT NULL, " +
        //                    "\"Random\" VARCHAR(50) NOT NULL, " +
        //                    "\"SpecVer\" NVARCHAR(50) NOT NULL, " +
        //                    "\"ConfigVer\" NVARCHAR(50) NOT NULL, " +
        //                    "\"EffTime\" DATETIME NOT NULL, " +
        //                    "\"Effective\" NVARCHAR(10) NOT NULL, " +
        //                    "\"Remark\" NVARCHAR(100), " +
        //                    "\"XML\" XML, " +
        //                    ");";
        //    try
        //    {
        //        MicroDBHelper.ExecuteNonQuery(strSql, null);
        //    }
        //    catch(Exception ex)
        //    {
        //        return false;
        //    }
        //    return true;
        //}

        //public static List<string> getConfigColNames()
        //{
        //    List<string> names = new List<string>();
        //    names.Add("ID");
        //    names.Add("ProCode");
        //    names.Add("TestNo");
        //    names.Add("SaveNo");
        //    names.Add("PIMItemName");
        //    names.Add("PIMType");
        //    names.Add("ProCH");
        //    names.Add("KEYWP");
        //    names.Add("IsSweepTest");
        //    names.Add("F1Freq");
        //    names.Add("F2Freq");
        //    names.Add("PIMFreq");
        //    names.Add("TXH");
        //    names.Add("TXL");
        //    names.Add("RXH");
        //    names.Add("RXL");
        //    names.Add("F1Power");
        //    names.Add("F2Power");
        //    names.Add("PIMOrder");
        //    names.Add("TestTime");
        //    names.Add("RXStep");
        //    names.Add("SpecReg");
        //    names.Add("SpecUnit");
        //    names.Add("IsKnock");
        //    names.Add("ProGain");
        //    names.Add("Message");
        //    names.Add("Check");
        //    names.Add("Random");
        //    names.Add("SpecVer");
        //    names.Add("ConfigVer");
        //    names.Add("EffTime");
        //    names.Add("Effective");
        //    names.Add("Remark");
        //    return names;
        //}

        public static List<string> getConfigColNames()
        {
            List<string> names = new List<string>();
            names.Add("ID");
            names.Add("产品代码");
            names.Add("测试顺序");
            names.Add("保存顺序");
            names.Add("测试项名称");
            names.Add("PIM类型");
            names.Add("通道");
            names.Add("关键工序");
            names.Add("是否扫频");
            names.Add("点频F1");
            names.Add("点频F2");
            names.Add("点频PIM");
            names.Add("扫频TX结束");
            names.Add("扫频TX起始");
            names.Add("扫频RX结束");
            names.Add("扫频RX起始");
            names.Add("功率1");
            names.Add("功率2");
            names.Add("阶数");
            names.Add("敲击或点频时间");
            names.Add("扫频RX步进");
            names.Add("测试要求");
            names.Add("单位");
            names.Add("是否敲击");
            names.Add("增益");
            names.Add("提示");
            names.Add("Check值");
            names.Add("Random值");
            names.Add("工艺文件版本");
            names.Add("配置文件版本");
            names.Add("生效时间");
            names.Add("有效性");
            names.Add("备注");
            names.Add("TXOffset");
            names.Add("测试频段");
            return names;
        }

        public static string getConfigColNamesStr()
        {
            string[] lstCol = getConfigColNames().ToArray();
            string sColNames = "";
            for (int i = 2; i < lstCol.Length - 1; i++)
            {
                if (i != lstCol.Length - 1 - 1)
                    sColNames += "[" + lstCol[i] + "],";
                else
                    sColNames += "[" + lstCol[i] + "]";
            }
            return sColNames;
        }

        public static List<string> getPIMColNames()
        {
            List<string> names = new List<string>();
            names.Add("通道");
            names.Add("测试类型");
            names.Add("交调类型");
            names.Add("频带信息");
            names.Add("阶数");
            names.Add("测试要求");
            names.Add("测试值");
            names.Add("判定结果");
            names.Add("实时测试值");
            return names;
        }

        public static ClsDataConfig[] Deserialize(string xmlFilePath)
        {
            try
            {
                var xmlSerializer = new XmlSerializer(typeof(ClsDataConfig[]));
                var sr = new StreamReader(xmlFilePath);

                var SerializerObject = (ClsDataConfig[])xmlSerializer.Deserialize(sr);
                sr.Close();

                return SerializerObject;
            }
            catch (Exception ex)
            {
                System.Windows.Forms.MessageBox.Show(ex.Message);
                return null;
            }
        }

        public static string Serialize(ClsDataConfig[] serializerObject, string xmlFilePath)
        {
            try
            {
                var xmlSerializer = new XmlSerializer(typeof(ClsDataConfig[]));
                StringWriter writer = new StringWriter();
                xmlSerializer.Serialize(writer, serializerObject);

                return XmlUtil.FormatXml(writer.ToString());
            }
            catch (Exception ex)
            {
                System.Windows.Forms.MessageBox.Show(ex.Message);
                return "";
            }
        }

        public static ClsDataConfig[] DeserializeString(string origin)
        {
            try
            {
                ClsDataConfig[] SerializerObject;
                var xmlSerializer = new XmlSerializer(typeof(ClsDataConfig[]));
                using (TextReader reader = new StringReader(origin))
                {
                    SerializerObject = (ClsDataConfig[])xmlSerializer.Deserialize(reader);
                }

                return SerializerObject;
            }
            catch (Exception ex)
            {
                System.Windows.Forms.MessageBox.Show(ex.Message);
                return null;
            }
        }

        public static string SerializeString(ClsDataConfig[] serializerObject)
        {
            try
            {
                var xmlSerializer = new XmlSerializer(typeof(ClsDataConfig[]));
                StringBuilder sb = new StringBuilder();
                XmlWriter writer = XmlWriter.Create(sb, new XmlWriterSettings() { OmitXmlDeclaration = true });
                xmlSerializer.Serialize(writer, serializerObject);
                writer.Close();

                return XmlUtil.FormatXml(sb.ToString());
            }
            catch (Exception ex)
            {
                System.Windows.Forms.MessageBox.Show(ex.Message);
                return "";
            }
        }

        public static DataTable toTable(List<ClsDataConfig> config)
        {
            DataTable dtConfig = new DataTable();
            var list = getConfigColNames();
            for (int i = 2; i < list.Count; i++)
            {//构建表
                dtConfig.Columns.Add(list[i]);
            }

            for (int i = 0; i < config.Count; i++)
            {//赋值
                DataRow row = dtConfig.NewRow();
                config[i].setRow(row);
                dtConfig.Rows.Add(row);
            }

            return dtConfig;
        }

        public static List<ClsDataConfig> toListConfig(string sID, string sCode, DataTable table)
        {
            if (table == null || table.Rows.Count == 0) return null;
            List<ClsDataConfig> lstConfig = new List<ClsDataConfig>();

            try
            {
                for (int i = 0; i < table.Rows.Count; i++)
                {
                    ClsDataConfig config = new ClsDataConfig();
                    config.setValues(Convert.ToInt32(sID), sCode, table.Rows[i]);
                    lstConfig.Add(config);
                }
            }
            catch { return null; }

            return lstConfig;
        }

        #endregion

        public bool getEffVer(out string configVer,  out string specVer, out string[] EffVer)
        {//通过产品代码查找产品ID
            float fMaxVer = 0;
            List<string> feffVer = new List<string>();
            foreach (DictionaryEntry deObj in m_nodePairs)
            {
                ProcodeINFO info = deObj.Value as ProcodeINFO;
                if (!info.bEffective) continue;
                float fVer = Convert.ToSingle(info.sConfigVer);
                feffVer.Add(fVer.ToString("0.0"));
                if (fMaxVer < fVer)
                {
                    m_cProceodeINFO = info;
                    m_sProcodeID = m_cProceodeINFO.sID;

                    m_sProcode = m_cProceodeINFO.sProCode;
                    m_sVerConfig = m_cProceodeINFO.sConfigVer;
                    m_sVerSpec = m_cProceodeINFO.sSpecVer;

                    fMaxVer = fVer;
                }
            }
            string[] effVer = feffVer.ToArray();
            EffVer = effVer;
            configVer = m_sVerConfig;
            specVer = m_sVerSpec;
            return true;
        }

        public bool upload(ProcodeINFO procodeNew, List<ClsDataConfig> SerializerObject, ref string error_info)
        {//上传新版本的配置
            string strXml = SerializeString(SerializerObject.ToArray());
            if (strXml == "")
            {
                return false;
            }

            return uploadXml(procodeNew, strXml, ref error_info);
        }

        public bool update(bool bEffective, List<ClsDataConfig> SerializerObject)
        {
            string strXml = "";
            if (SerializerObject != null)
            {
                strXml = SerializeString(SerializerObject.ToArray());
                if (strXml == "")
                {
                    return false;
                }
            }

            return updateXml(bEffective, strXml);
        }

        public bool update(bool bEffective, DataTable table)
        {
            string strXml = "";
            if (table != null || table.Rows.Count == 0)
            {
                List<ClsDataConfig> lstConfig = toListConfig(this.m_sProcodeID, this.m_sProcode, table);
                if (lstConfig == null || lstConfig.Count == 0)
                {
                    return false;
                }

                strXml = SerializeString(lstConfig.ToArray());
                if (strXml == "")
                {
                    return false;
                }
            }

            return updateXml(bEffective, strXml);
        }

        public List<ClsDataConfig> download()
        {//下载当前版本的配置
            string sXml = downloadXml();
            if (sXml != null && sXml != "")
            {
                var lstConfig = new List<ClsDataConfig>();
                lstConfig.AddRange(DeserializeString(sXml));
                return lstConfig;
            }
            return null;
        }

        public List<ClsDataConfig> download(out DataTable dtPIMTest, ref string error_info)
        {
            dtPIMTest = null;
            var lstConfig = download();
            if (lstConfig == null) return null;

            dtPIMTest = new DataTable();
            List<string> lstPIMTestColNames = getPIMColNames();
            for (int i = 0; i < lstPIMTestColNames.Count; i++)
                dtPIMTest.Columns.Add(lstPIMTestColNames[i]);

            for (int i = 0; i < lstConfig.Count; i++)
            {
                DataRow dr = dtPIMTest.NewRow();
                //"通道"
                dr[0] = lstConfig[i].ProCH;
                //"测试类型"
                dr[1] = PIMFunction.getPIMTestType(lstConfig[i]);
                //"交调类型"
                dr[2] = lstConfig[i].PIMType;
                //"频带信息"
                dr[3] = PIMFunction.getPIMTestBandInfo(lstConfig[i]);
                //"交调阶数"
                dr[4] = lstConfig[i].PIMOrder;
                //"测试要求值"
                dr[5] = lstConfig[i].SpecReg;
                //"测试值"
                dr[6] = "";
                //"判定结果"
                dr[7] = "";
                //"实时测试值"
                dr[8] = "";
                dtPIMTest.Rows.Add(dr);
            }
            return lstConfig;
        }
    }
}
